package com.tanhua.admin.service;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.admin.mapper.AnalysisMapper;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.domain.Analysis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class AnalysisService {

    @Autowired
    private LogMapper logMapper;
    @Autowired
    private AnalysisMapper analysisMapper;

    /**
     * 定时统计tb_log中的数据，保存或更新analysis表中的数据
     * 1.查询tb_log表（注册用户数，登录用户数，活跃用户数，次日留存的用户数：指的是昨日注册，今日活跃的用户）
     * 2.构造analysis对象
     * 3.保存或更新
     */
    public void analysis() throws ParseException {
        //定义查询日期
        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        //统计数据：注册数量
        Integer registerCount = logMapper.queryByTypeAndLogTime("0102", today);
        //统计数据：登录数量
        Integer loginCount = logMapper.queryByTypeAndLogTime("0101", today);
        //统计数据：活跃数量
        Integer activeCount = logMapper.queryByLogTime(today);
        //统计数据：次日留存数量
        Integer numRetention1d = logMapper.queryNumRetention1d(today, yesterday);

        //根据日期查询数据
        QueryWrapper<Analysis> wrapper = new QueryWrapper<>();
        wrapper.eq("record_date", new SimpleDateFormat("yyyy-MM-dd").parse(today));
        Analysis analysis = analysisMapper.selectOne(wrapper);

        if (analysis != null) {
            //如果存在：更新
            analysis.setNumRegistered(registerCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysisMapper.updateById(analysis);
        } else {
            //不存在：保存
            analysis = new Analysis();
            analysis.setNumRegistered(registerCount);
            analysis.setNumLogin(loginCount);
            analysis.setNumActive(activeCount);
            analysis.setNumRetention1d(numRetention1d);
            analysis.setRecordDate(new SimpleDateFormat("yyyy-MM-dd").parse(today));
            analysis.setCreated(new Date());
            analysis.setUpdated(new Date());
            analysisMapper.insert(analysis);
        }
    }
}
